package com.qcb.expresswrapping.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qcb.expresswrapping.common.Result;
import com.qcb.expresswrapping.entity.*;
import com.qcb.expresswrapping.service.StationExpressService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.Date;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @author: QCB
 * @create: 2022-03-12-23:13
 * To change this template use File | Settings | File and Code Templates.
 */
@RestController
@RequestMapping("/dm/logistics")
public class DmLogisticsInfoController extends BaseController{

    @GetMapping("/info/{logisticsId}")
    @PreAuthorize("hasAnyAuthority('dm:logistics:list')")
    public Result info(@PathVariable("logisticsId") String logisticsId){
        LogisticsInfo logisticsInfo = logisticsInfoService.getById(logisticsId);
        Assert.notNull(logisticsInfo, "查无此纪录");
        return Result.success(logisticsInfo);
    }


    @GetMapping("/stationlist")
    @PreAuthorize("hasAnyAuthority('dm:logistics:stationlist')")
    public Result stationlist(){
        List<StationInfo> stationInfoList = scStationInfoService.list();
        return Result.success(stationInfoList);
    }

    @Transactional
    @PostMapping("/save/{orderId}/{expressId}")
    @PreAuthorize("hasAnyAuthority('dm:logistics:save')")
    public Result save(@Validated @RequestBody LogisticsInfo logisticsInfo, @PathVariable("orderId") String orderId,
                       @PathVariable("expressId") Integer expressId, Principal principal){
        SendOrder sendOrder = scSendOrderService.getById(orderId);
        sendOrder.setStatus(2);
        scSendOrderService.updateById(sendOrder);
        int step = orderLogisticsService.count(new QueryWrapper<OrderLogistics>()
        .eq("orderId", orderId));
        String logisticsId = orderId + (step + 1);
        logisticsInfo.setLogisticsId(logisticsId);
        logisticsInfo.setCourierId(sysUserService.getByUsername(principal.getName()).getId());
        logisticsInfo.setStep(step+1);
        logisticsInfo.setDepartTime(new Date());
        logisticsInfo.setStatus(0);
        logisticsInfoService.save(logisticsInfo);

        OrderLogistics orderLogistics = new OrderLogistics();
        orderLogistics.setOrderId(orderId);
        orderLogistics.setLogisticsId(logisticsId);
        orderLogisticsService.save(orderLogistics);

        StationExpress stationExpress = scStationExpressService.getById(expressId);
        stationExpress.setStatus(1);
        scStationExpressService.updateById(stationExpress);
        return Result.success(logisticsInfo);
    }

    @PostMapping("/update")
    @PreAuthorize("hasAnyAuthority('dm:logistics:update')")
    public Result update(@Validated @RequestBody LogisticsInfo logisticsInfo){
        logisticsInfoService.updateById(logisticsInfo);
        return Result.success(logisticsInfo);
    }

    @GetMapping("/list")
    @PreAuthorize("hasAnyAuthority('dm:logistics:list')")
    public Result list(Date departTime, Integer status, Principal principal){
        Page<LogisticsInfo> pageData = logisticsInfoService.page(getPage(), new QueryWrapper<LogisticsInfo>()
        .eq("courierId", sysUserService.getByUsername(principal.getName()).getId())
                .ge(departTime!= null, "departTime", departTime)
                .eq(status != null, "status", status)
                .orderByAsc("status")
        );
        return Result.success(pageData);
    }

    @Transactional
    @GetMapping("/serviced/{logisticsId}")
    @PreAuthorize("hasAnyAuthority('dm:logistics:serviced')")
    public Result serviced(@PathVariable("logisticsId") String logisticsId){
        LogisticsInfo logisticsInfo = logisticsInfoService.getById(logisticsId);
        logisticsInfo.setArriveTime(new Date());
        logisticsInfo.setStatus(1);
        logisticsInfoService.updateById(logisticsInfo);
        List<StationInfo> address = scStationInfoService.list(new QueryWrapper<StationInfo>()
                .eq("address", logisticsInfo.getTargetSite()));
        StationExpress stationExpress = new StationExpress();
        stationExpress.setStationId(address.get(0).getAccountId());
        stationExpress.setEnterDate(new Date());
        stationExpress.setStatus(0);
        stationExpress.setOrderId(logisticsInfo.getLogisticsId().substring(0, logisticsInfo.getLogisticsId().length()-1));
        scStationExpressService.save(stationExpress);
        return Result.success(logisticsInfo);
    }

    @GetMapping("/expresslist")
    @PreAuthorize("hasAnyAuthority('dm:logistics:expresslist')")
    public Result expresslist(Integer stationId){
        Page<StationExpress> pageData = scStationExpressService.page(getPage(), new QueryWrapper<StationExpress>()
                .eq(stationId != null, "stationId", stationId)
                .eq("status", 0)
        );
        pageData.getRecords().forEach(u ->{
            u.setStationInfo(scStationInfoService.getById(u.getStationId()));
            u.setSendOrder(scSendOrderService.getById(u.getOrderId()));
        });
        return Result.success(pageData);
    }

    @GetMapping("/expressinfo/{id}")
    @PreAuthorize("hasAnyAuthority('dm:logistics:expresslist')")
    public Result expressinfo(@PathVariable("id") Integer id){
        StationExpress stationExpress = scStationExpressService.getById(id);
        stationExpress.setStationInfo(scStationInfoService.getById(stationExpress.getStationId()));
        stationExpress.setSendOrder(scSendOrderService.getById(stationExpress.getOrderId()));
        return Result.success(stationExpress);
    }
}
